package net.starwifi.duobao.web;


import net.starwifi.duobao.AppInitListener;
import net.starwifi.duobao.entity.DBOrder;
import net.starwifi.duobao.entity.DBProduct;
import net.starwifi.duobao.entity.DBTimes;
import net.starwifi.duobao.entity.Member;
import net.starwifi.duobao.mvc.Filter;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.mvc.Order;
import net.starwifi.duobao.mvc.PageView;
import net.starwifi.duobao.rmi.AppRMIUtils;
import net.starwifi.duobao.service.*;
import net.starwifi.duobao.utils.IpUtils;
import net.starwifi.duobao.utils.sms.SMSUtils;
import net.starwifi.duobao.utils.times.DateTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 夺宝期数
 * Created by Administrator on 2015/11/19.
 */
@Controller("adminDBTimesController")
@RequestMapping("/dbTimes")
public class DBTimesController extends BaseController{

    @Autowired
    DBTimesService dbTimesService;

    @Autowired
    DBProductService dbProductService;

    @Autowired
    StaticService staticService;

    @Autowired
    DBTimesDataService dbTimesDataService;

    @Autowired
    DBOrderService dbOrderService;

    @Autowired
    MemberService memberService;

    @Autowired
    PaymentService paymentService;


    @Autowired
    private ServletContext servletContext;

   /* *//**
     * 校准夺宝码
     *//*
    @ResponseBody
    @RequestMapping(value = "/reBuild", method = RequestMethod.GET)
    public Message reBuild(ModelMap model,Long timesId) {
        DBTimes dbTimes=dbTimesService.find(timesId);
        dbTimesDataService.reBuildDBTimesPool(dbTimes);
        return Message.success("success");
    }


    *//**
     * 添加
     *//*
    @ResponseBody
    @RequestMapping(value = "/reCode", method = RequestMethod.GET)
    public Message reCode(ModelMap model,Long timesId) {
        DBTimes dbTimes=dbTimesService.find(timesId);
        if(!dbTimes.getIsLottery()){
            dbTimesDataService.reCode(dbTimes);
        }
        return Message.success("success");
    }*/


    /**
     * 添加
     */
    @RequestMapping(value = "/putOrder", method = RequestMethod.GET)
    public String putOrder(ModelMap model,Long timesId) {
        model.addAttribute("dbTimes",dbTimesService.find(timesId));
        return "/dbTimes/putOrder";
    }


    /**
     * 编辑
     */
    @RequestMapping(value = "/putOrderUpdate", method = RequestMethod.POST)
    public String putOrderUpdate(Long timesId,String mobile,int count,String ip, ModelMap model,HttpServletRequest request,RedirectAttributes redirectAttributes) {
        DBTimes dbTimes=dbTimesService.find(timesId);
        if(dbTimes!=null){
            Member member= memberService.findByMobile(mobile);;
            if(member==null){
                addFlashMessage(redirectAttributes, Message.error("用户不存在，请先添加用户"));
                return "redirect:/dbTimes/putOrder?timesId="+timesId;
            }
            if(dbTimes==null){ //已经结束的不能购买
                addFlashMessage(redirectAttributes, Message.error("该夺宝期不存在"));
                return "redirect:/dbTimes/putOrder?timesId="+timesId;
            }
            if(count>dbTimes.getPurchaseQuantity()){
                addFlashMessage(redirectAttributes, Message.error("超过数量限制"));
                return "redirect:/dbTimes/putOrder?timesId="+timesId;
            }
            if(dbTimes.getIsOver()){
                addFlashMessage(redirectAttributes, Message.error("该夺宝期已经结束,不能购买"));
                return "redirect:/dbTimes/putOrder?timesId="+timesId;
            }
            if(count<dbTimes.getStepNum()){
                addFlashMessage(redirectAttributes, Message.error("购买份数不能小于："+dbTimes.getStepNum()+"份"));
                return "redirect:/dbTimes/putOrder?timesId="+timesId;
            }
            if(count%dbTimes.getStepNum()!=0){
                addFlashMessage(redirectAttributes, Message.error("必须是："+dbTimes.getStepNum()+"的整数倍"));
                return "redirect:/dbTimes/putOrder?timesId="+timesId;
            }
            if(dbTimes.getCurrentQuantity()+count>dbTimes.getQuantity()){
                addFlashMessage(redirectAttributes, Message.error("仅剩下"+(dbTimes.getQuantity()-dbTimes.getCurrentQuantity())+"份库存"));
                return "redirect:/dbTimes/putOrder?timesId="+timesId;
            }
            String orderSn=AppInitListener.idGenerate.getID().toString();
            String ipAddress=IpUtils.getIpAddress(ip);
            final DBOrder order=dbOrderService.build(dbTimes.getDbProduct(),member,orderSn,dbTimes.getTimesNo(),count,ip,ipAddress);
            AppRMIUtils.rmiApi("dbOrder",order.getId()+"");
            addFlashMessage(redirectAttributes, Message.success("添加成功"));
        }
        return "redirect:/dbTimes/listAll";
    }


    /**
     * 添加
     */
    @RequestMapping(value = "/wantLottery", method = RequestMethod.GET)
    public String wantLottery(ModelMap model,Long timesId,Long orderId) {
        model.addAttribute("dbTimes",dbTimesService.find(timesId));
        model.addAttribute("dbOrder",dbOrderService.find(orderId));
        return "/dbTimes/wantLottery";
    }

    /**
     * 编辑
     */
    @RequestMapping(value = "/wantLotteryUpdate", method = RequestMethod.POST)
    public String wantLottery(Long timesId,Long orderId,HttpServletRequest request,RedirectAttributes redirectAttributes) {
        DBTimes dbTimes=dbTimesService.find(timesId);
        if(dbTimes!=null){
            if(dbTimes.getIsLottery()){
                addFlashMessage(redirectAttributes, Message.error("该夺宝期已经开奖"));
                return "redirect:/dbTimes/wantLottery?timesId="+timesId+"&orderId="+orderId;
            }
            DBOrder dbOrder=dbOrderService.find(orderId);
            if(!dbOrder.getTimesNo().equals(dbTimes.getTimesNo())){
                addFlashMessage(redirectAttributes, Message.error("订单号与订单的夺宝期不匹配"));
                return "redirect:/dbTimes/wantLottery?timesId="+timesId+"&orderId="+orderId;
            }
            if(dbOrder.getCodeInfo()==null){
                addFlashMessage(redirectAttributes, Message.error("该订单的夺宝码不正常"));
                return "redirect:/dbTimes/wantLottery?timesId="+timesId+"&orderId="+orderId;
            }
            dbTimesService.updateWantOrder(timesId,orderId);
            addFlashMessage(redirectAttributes, Message.success("修改成功"));
        }
        return "redirect:/dbTimes/listAll";
    }



    /**
     * 添加
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(ModelMap model,Long productId) {
        model.addAttribute("dbProduct",dbProductService.find(productId));
        return "/dbTimes/add";
    }

    /**
     * 保存
     */

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(DBTimes entity,Long productId, RedirectAttributes redirectAttributes) {
        DBProduct dbProduct=dbProductService.find(productId);
        entity.setInCount(0);
        entity.setTimesCode(0);
        entity.setIsLottery(Boolean.FALSE);
        entity.setIsOver(Boolean.FALSE);
        if(dbProduct.getIsMarketable()){
            addFlashMessage(redirectAttributes, Message.error("该产品尚未结束夺宝,不能发布新的夺宝活动"));
            return ERROR_VIEW;
        }
        if (!isValid(entity)) {
            return ERROR_VIEW;
        }
        String timesNo= AppInitListener.idGenerate.getDBID().toString(); //夺宝期数
        entity.setTimesNo(timesNo);
        entity.setDbProduct(dbProduct);
        entity.setCurrentQuantity(0); //当前已购买0份
        DBTimes dataDBTimes=dbTimesService.create(entity);  //从此处开始添加新的夺宝期....
        //更新产品关联
        dbProduct.setDbTimes(dataDBTimes);
        dbProduct.setIsMarketable(Boolean.TRUE);
        dbProductService.update(dbProduct);
        AppRMIUtils.buildDBIndex();
        AppRMIUtils.buildDBTimes(dataDBTimes.getId());
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:/dbTimes/list?productId="+productId;
    }


    /**
     * 编辑
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Long id, ModelMap model) {
        DBTimes dbTimes=dbTimesService.find(id);
        model.addAttribute("entity", dbTimes);
        Long dbCodeSize=dbTimesService.getPoolSize(dbTimes.getTimesNo());
        model.addAttribute("dbCodeSize",dbCodeSize);
        return "/dbTimes/edit";
    }

    /**
     * 编辑
     */
    @RequestMapping(value = "/showedit", method = RequestMethod.GET)
    public String showedit(Long id, ModelMap model) {
        DBTimes dbTimes=dbTimesService.find(id);
        model.addAttribute("entity", dbTimes);
        Long dbCodeSize=dbTimesService.getPoolSize(dbTimes.getTimesNo());
        model.addAttribute("dbCodeSize",dbCodeSize);
        return "/dbTimes/showedit";
    }

    /**
     * 更新
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(DBTimes entity,Long productId, RedirectAttributes redirectAttributes) {
        if (!isValid(entity)) {
            return ERROR_VIEW;
        }
        dbTimesService.update(entity,"dbProduct","timesNo","startDate","timesCode","isLottery","isOver","dbOrder");
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:/dbTimes/list?productId="+productId;
    }


    /**
     * 编辑
     */
    @RequestMapping(value = "/shipping", method = RequestMethod.GET)
    public String shipping(Long id, ModelMap model) {
        model.addAttribute("entity", dbOrderService.find(id));
        return "/dbTimes/shipping";
    }

    /**
     * 编辑
     */
    @ResponseBody
    @RequestMapping(value = "/lotterySMS", method = RequestMethod.POST)
    public Object lotterySMS(Long id) {
       DBTimes dbTimes=dbTimesService.find(id);
        if(dbTimes==null){
            return Message.error("夺宝期不存在");
        }
        //SMSUtils.send(dbTimes.getLotteryMobile(), "http://dwz.cn/2gMpQT", "10012");
        return Message.success("发送中奖提醒成功");
    }


    /**
     * 编辑
     */
    @ResponseBody
    @RequestMapping(value = "/shippingUpdate", method = RequestMethod.POST)
    public Object shippingUpdate(Long orderId,String shippingMethodName,String shippingSn, ModelMap model) {
        DBOrder dbOrder=dbOrderService.find(orderId);
        if(!dbOrder.getIsLottery()){
             return Message.error("订单中奖情况有误,请核实");
        }
        if(dbOrder.getConsignee()==null){
            return Message.error("配送信息有误,请核实");
        }
        dbOrder.setShippingStartDate(new Date());
        dbOrder.setShippingMethodName(shippingMethodName);
        dbOrder.setShippingSn(shippingSn);
        dbOrder.setShippingStatus(1);
        dbOrderService.update(dbOrder);
        return Message.success("更新夺宝物流信息成功");
    }


    /**
     * 列表
     */
    @RequestMapping(value = "/listAll", method = RequestMethod.GET)
    public String list(PageView pageView,ModelMap model,HttpServletRequest request) {
        pageView.filterQuery(request);
        pageView.addOrder(Order.desc("id"));
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        model.addAttribute("currentDate",format.format(new Date()));
        Date beginData= DateTool.setHms(new Date(), 0, 0, 0);
        Date endData= DateTool.setHms(new Date(),23,59,59);
        model.addAttribute("beginData", beginData);
        model.addAttribute("endData", endData);
        model.addAttribute("dbProductList",dbProductService.getListData());
        model.addAttribute("page", dbTimesService.getScrollData(pageView));
        return "/dbTimes/listAll";
    }


    /**
     * 列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(PageView pageView, Long productId,ModelMap model,HttpServletRequest request) {
        pageView.filterQuery(request);
        pageView.addFilter(Filter.eq("dbProduct.id",productId));
        pageView.addOrder(Order.desc("id"));
        model.addAttribute("dbProduct", dbProductService.find(productId));
        model.addAttribute("page", dbTimesService.getScrollData(pageView));
        return "/dbTimes/list";
    }


    /**
     * 列表
     */
    @ResponseBody
    @RequestMapping(value = "/jsonList", method = RequestMethod.GET)
    public Object list(Long productId) {
        List<Order> orderBy=new ArrayList<Order>();
        orderBy.add(Order.desc("id"));
        final List<DBTimes> list=dbTimesService.getListData("o.dbProduct.id=?1",new Object[]{productId},orderBy);
        return Message.createMessage(Message.success("success"), new HashMap<String, Object>() {{
            put("list", list);
        }});
    }

    /**
     * 删除
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Message delete(Long[] ids) {
        dbTimesService.delete(ids);
        return SUCCESS_MESSAGE;
    }
    /**
     * 导出Excel
     * */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public String  exportExcel(PageView pageView,HttpServletRequest request,ModelMap model) throws IOException {
        pageView.filterQuery(request);
        pageView.getOrders().add(Order.desc("id"));
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String url=dbTimesService.exportExcel2003WithUsermodel(format.format(new Date()), servletContext.getRealPath("/"), pageView);
        model.addAttribute("message","Excel生成成功");
        model.addAttribute("content","<a href='/"+url+"' target=\"_blank\">点击下载</a>");
        return "/common/handle";
    }

}
